package com.weizhong.update.service;

import java.io.File;

import android.app.DownloadManager;import android.app.Notification;import android.app.NotificationManager;import android.app.PendingIntent;import android.app.Service;import android.app.DownloadManager.Request;import android.content.BroadcastReceiver;import android.content.Context;import android.content.Intent;import android.content.IntentFilter;import android.database.ContentObserver;import android.database.Cursor;import android.net.Uri;import android.os.Environment;import android.os.Handler;import android.os.IBinder;import android.os.Looper;import android.os.Message;import android.os.PowerManager;import android.text.TextUtils;import android.util.Log;import android.view.View;import android.widget.RemoteViews;import android.widget.Toast;

import com.weizhong.update.R;import com.weizhong.update.util.Constances;import com.weizhong.update.util.DialogUpdateActivity;import com.weizhong.update.util.FileTool;import com.weizhong.update.util.Logger;import com.weizhong.update.util.UpdateDetail;

public class UpdateDownloadListener{	public static final Uri CONTENT_URI = Uri.parse("content://downloads/my_downloads");  
	private static final String TAG = "UpdateDownloadListener";	
	private final int NOTIFY_ID=0;		// 通知栏
	private NotificationManager updateNotificationManager = null;		// 通知栏跳转Intent
	private Intent updateIntent = null;	private long lastDownloadId = -1;	//
	private PowerManager.WakeLock wakeLock = null; 
	private Context mContext = null;	private Notification updateNotification = null;	private DownloadManager dowanloadmanager = null;	DownloadChangeObserver downloadObserver = new DownloadChangeObserver(null); 		private static UpdateDownloadListener mUpdateDownloadListener = null;		public static int checkAndStartup(Context context,long downloadid){		if (mUpdateDownloadListener == null){			mUpdateDownloadListener = new UpdateDownloadListener(context);		}				mUpdateDownloadListener.checkAndStartup(downloadid);				return 1;	}			public UpdateDownloadListener(Context context){		mContext = context;	     
	}		private DownloadManager getDownloadManager(){		if (dowanloadmanager==null)			dowanloadmanager = (DownloadManager)mContext.getSystemService(mContext.DOWNLOAD_SERVICE);		return dowanloadmanager;	}		public void checkAndStartup(long downloadid){		Log.i(TAG,"checkAndStartup downloadid: "+ downloadid			+ "lastDownloadId: " + lastDownloadId);		//检测启动		if (lastDownloadId != downloadid){			cancelNotification();			lastDownloadId = downloadid;		}		queryDownloadStatus();	}	/**     * 退出notification     */    private void cancelNotification(){    	if(null!=updateNotificationManager){    		if (null!=updateNotification){
    			updateNotificationManager.cancel(NOTIFY_ID);    			updateNotification = null;    	  		mContext.getContentResolver().unregisterContentObserver(downloadObserver);    	  		stopTimer();    	  		oldstatus = -2000;    		}    	}    }
    /**  	 * notification提示
  	 * @param intent
  	 */
  	private void createNotification(Context context,int status,int pos){
  		Logger.i(TAG, "createNotification");  		if (this.updateNotification != null) return;  		
  		if(null==this.updateNotificationManager){  			this.updateNotificationManager = (NotificationManager) context.getSystemService(context.NOTIFICATION_SERVICE);
  		}
  		this.updateNotification = new Notification();  		  		updateNotification.flags= Notification.FLAG_NO_CLEAR;
  		// 设置下载过程中，点击通知栏，回到主界面 this, UpdateActivity.class  		RemoteViews contentView = new RemoteViews(context.getPackageName(), R.layout.download_notification_layout);          contentView.setTextViewText(R.id.fileName,getStatusText(status));          contentView.setProgressBar(R.id.progress, 100, pos, false);
        // 指定个性化视图  
        updateNotification.contentView = contentView;        
  		// 设置通知栏显示内容
  		updateNotification.icon = R.drawable.ic_launcher;  		Intent intent = new Intent(context,DialogUpdateActivity.class);  		intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);        PendingIntent pendingIntent  = PendingIntent.getActivity(context, 0, intent, 0);          updateNotification.contentIntent = pendingIntent;           
  		updateNotification.tickerText = context.getResources().getText(R.string.notification_string);
  		// 通知不被清理
  		updateNotification.flags |= Notification.FLAG_NO_CLEAR;
  		// 发出通知
  		updateNotificationManager.notify(NOTIFY_ID, updateNotification);  	  		oldstatus = status;  		startTimer(); 		  	}  	  	private String getStatusText(int status){  		  		String txt = mContext.getResources().getString(R.string.notification_string);  		  		switch(status) {             case DownloadManager.STATUS_PAUSED:         	txt += "(等待中)";             break;        case DownloadManager.STATUS_PENDING:            txt += "(等待中)";            break;        case DownloadManager.STATUS_RUNNING:       			            //正在下载，不做任何事情        	txt += "(下载中)";            break;       			        case DownloadManager.STATUS_SUCCESSFUL:                 //完成            	txt += "(已完成)";            break;             case DownloadManager.STATUS_FAILED:                 //清除已下载的内容，重新下载                txt += "(失败)";            break;             }       		  		return txt;  		  	}  	  	boolean  isTimeRun = false;  	  	private void startTimer(){  		if (isTimeRun==false){  			isTimeRun = true;  			downloadObserver = new DownloadChangeObserver(null);        			mContext.getContentResolver().registerContentObserver(CONTENT_URI, true, downloadObserver);  		}		  	  	}  	  	private void stopTimer(){  		if (isTimeRun){  			isTimeRun = false;  			mContext.getContentResolver().unregisterContentObserver(downloadObserver);//registerContentObserver(CONTENT_URI, true, downloadObserver);  			downloadObserver = null;  		}  	}  	  	  	private int oldstatus = -2000;  	private void setNotificationProgressStatus(int status,int pos){  		if (pos > 100) pos = 100;  		if (this.updateNotification==null){  			createNotification(mContext,status,pos);  			if (this.updateNotification==null) return;  		}  		this.updateNotification.contentView.setProgressBar(R.id.progress, 100, pos, false);  		this.updateNotification.contentView.setTextViewText(R.id.rate, "" + pos + "%");  		if (oldstatus != status){  			this.updateNotification.contentView.setTextViewText(R.id.fileName,getStatusText(status));  			oldstatus = status;  		}  		updateNotificationManager.notify(NOTIFY_ID, updateNotification);  	}  	  	  	private int queryDownloadStatus() {   		 //比如要监听实时下载进度，查看当前下载状态：是否已经断开，或者下载失败等等  		DownloadManager.Query query = new DownloadManager.Query();       		query.setFilterById(lastDownloadId);		Log.i(TAG,"queryDownloadStatus lastDownloadId: " + lastDownloadId);  		Cursor c = getDownloadManager().query(query);       		if(c!=null&&c.moveToFirst()) {   			//找到数据  			int status = c.getInt(c.getColumnIndex(DownloadManager.COLUMN_STATUS));                 int reasonIdx = c.getColumnIndex(DownloadManager.COLUMN_REASON);                int titleIdx = c.getColumnIndex(DownloadManager.COLUMN_TITLE);                int fileSizeIdx = c.getColumnIndex(DownloadManager.COLUMN_TOTAL_SIZE_BYTES);                    int bytesDLIdx =   c.getColumnIndex(DownloadManager.COLUMN_BYTES_DOWNLOADED_SO_FAR);                String title = c.getString(titleIdx);                int fileSize = c.getInt(fileSizeIdx);                int bytesDL = c.getInt(bytesDLIdx);              int reason = c.getInt(reasonIdx);                StringBuilder sb = new StringBuilder();                sb.append(title).append("\n");               sb.append("Downloaded ").append(bytesDL).append(" / " ).append(fileSize);             Log.d("tag", sb.toString());              switch(status) {                 case DownloadManager.STATUS_PAUSED:                 Log.v("tag", "STATUS_PAUSED");                 setNotificationProgressStatus(status,(int)(((double)(bytesDL)/fileSize)*100));                break;            case DownloadManager.STATUS_PENDING:                Log.v("tag", "STATUS_PENDING");                setNotificationProgressStatus(status,(int)(((double)(bytesDL)/fileSize)*100));                break;            case DownloadManager.STATUS_RUNNING:       			                //正在下载，不做任何事情      			            	setNotificationProgressStatus(status,(int)(((double)(bytesDL)/fileSize)*100));                Log.v("tag", "STATUS_RUNNING");                    break;       			            case DownloadManager.STATUS_SUCCESSFUL:                     //完成                	cancelNotification();                Log.v("tag", "下载完成");                      break;                 case DownloadManager.STATUS_FAILED:                     //清除已下载的内容，重新下载                	setNotificationProgressStatus(status,(int)(((double)(bytesDL)/fileSize)*100));                Log.v("tag", "STATUS_FAILED");                getDownloadManager().remove(lastDownloadId);                cancelNotification();                Toast.makeText(mContext, "系统更新文件下载异常中断，", Toast.LENGTH_LONG).show();                  break;                 }     		}  	    if (c!=null) c.close();  	    c = null;  		return 1;  	}  	    private class DownloadChangeObserver extends ContentObserver {         public DownloadChangeObserver(Uri uri) {             super(new Handler());                     }                  @Override         public void onChange(boolean selfChange) {             //查询需要监听的字段        	 queryDownloadStatus();                      }     }
}
